package com.example.lenovo.popupwindow;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private PopupWindow mpopupWindow;
    private Button mbtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mbtn=findViewById(R.id.btn);
        mbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow();
            }
        });
    }

    private void showPopupWindow() {
        View contenView= LayoutInflater.from(MainActivity.this).inflate(R.layout.popupwindow,null);
        mpopupWindow=new PopupWindow(contenView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,true);
        TextView tv1 = contenView.findViewById(R.id.item1);
        TextView tv2 = contenView.findViewById(R.id.item2);
        TextView tv3 = contenView.findViewById(R.id.item3);
        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
        tv3.setOnClickListener(this);
        //显示PopupWindow  
        View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
        mpopupWindow.setOutsideTouchable(true);
        mpopupWindow.setTouchable(true);
        mpopupWindow.setFocusable(true);
        mpopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mpopupWindow.update();
        mpopupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        mpopupWindow.setHeight(ViewGroup.LayoutParams.FILL_PARENT);
        mpopupWindow.showAtLocation(rootview, Gravity.BOTTOM,0,0);
       //mpopupWindow.showAsDropDown(mbtn,0,0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.item1:
                Toast.makeText(this, "点击了item1", Toast.LENGTH_SHORT).show();
                mpopupWindow.dismiss();
                break;
            case R.id.item2:
                Toast.makeText(this, "点击了item2", Toast.LENGTH_SHORT).show();
                mpopupWindow.dismiss();
                break;
            case R.id.item3:
                Toast.makeText(this, "点击了item3w", Toast.LENGTH_SHORT).show();
                mpopupWindow.dismiss();
                break;

        }
    }
}
